<?php


    /**
     * Returns the version.
     *
     * @return string of application version
     */

    function ver()
    {
        return '1.0.0';
    }

if (!function_exists('uuid')) {
    /**
     * Generate a UUID (version 4).
     *
     * @return string
     */
    function uuid(): string
    {
        return \Illuminate\Support\Str::uuid()->toString();
		// 或直接 \Ramsey\Uuid\Uuid::uuid4()->toString();
    }
}

if (! function_exists('str2arr')) {
	/**
	 * 字符串转换为数组，主要用于把分隔符调整到第二个参数
	 * @param  string $str  要分割的字符串
	 * @param  string $glue 分割符
	 * @return array
	 */
	function str2arr($str = '', $glue = ',') {
		if ($str) {
			if(is_array($str)){
				return $str;
			}else{
				return array_filter(explode($glue, $str));
			}
		} else {
			return array();
		}
	}
}

if (! function_exists('arr2str')) {
	/**
	 * 数组转换为字符串，主要用于把分隔符调整到第二个参数
	 * @param  array  $arr  要连接的数组
	 * @param  string $glue 分割符
	 * @return string
	 */
	function arr2str($arr = array(), $glue = ',') {
		if (empty($arr)) {
			return '';
		} else {
			if(is_array($arr)){
				return implode($glue, $arr);
			}else{
				return $arr;
			}
		}
	}
}

if (! function_exists('tag2arr')) {
	/**
	 * 数组转换为字符串，主要用于把分隔符调整到第二个参数
	 * @param  array  $arr  要连接的数组
	 * @param  string $glue 分割符
	 * @return string
	 */
	function tag2arr($tag) {
		$tag = str2arr($tag);
		$arr = [];
		foreach($tag as $v){
			$arr[$v] = $v;
		}
		return $arr;
	}
}

if (! function_exists('cate_model')) {
    /**
     * 获取指定应用的分类模型
	 * @param $app
     * @return \App\Models\Cate with Global Scope by app_name
     * 
     */
    function cate_model($app='')
    {
		if(empty($app)){
			return new \App\Models\Cate();
		}else{
			if($app instanceof \App\Models\App){
					$name = $app->name;  //直接app对象
			}elseif(is_array($app)){
					$name = $app['name']; //直接是app
			}else{
					$name = $app;
			}    
			return new \App\Models\Cate([$name]);
		}
    }
}

if (! function_exists('get_app')) {
	/**
	 * 获取应用信息
	 * @param  string  $field  
	 * @param  \App\Models\App||array||string $name
	 */
	function get_app($app,$field=false) {
		if($app instanceof \App\Models\App){
				$app = $app->toArray();  
		}elseif(!empty($app) && is_string($app)){
				$app = \App\Models\App::find($app);
				if(!empty($app)){
					$app = $app->toArray();		
				}
		}
		if(empty($app) || !is_array($app)) return false;
		//此处可写入应用缓存
		if($field){
			return $app[$field] ?? ''; 
		}else{
			return $app ;
		}
	}
}
if (! function_exists('get_cate')) {
	/**
	 * 获取应用信息
	 * @param  string  $field  
	 * @param  \App\Models\App||array||string $name
	 */
	function get_cate($cate,$field=false) {
		if($cate instanceof \App\Models\Cate){
			$cate = $cate->toArray();  //直接app对象
		}elseif(!empty($cate) && (is_string($cate) || is_numeric($cate)) ){
			$cate = \App\Models\Cate::where('name',$cate)->orWhere('id',$cate)->first();
			if(!empty($cate)){
				$cate = $cate->toArray();	
			}
		}
		if(empty($cate) || !is_array($cate)) return ($field) ? '' : [];
		//此处可写入应用缓存
		if($field){
			return $cate[$field] ?? ''; 
		}else{
			return $cate ;
		}
	}
}


if (! function_exists('get_app_cate')) {
	/**
	 * 获取应用分类信息
	 * @$appname  App\models\App||array||string  $app    
	 * @name string|int 分类名或cate_id
	 * @field string
	 * @return viod
	 */
	function get_app_cate($app,$cate) {	
		$app = get_app($app);
		
		$cate= get_cate($cate);
		
		if($cate && empty($app)){
			$app = get_app($cate['app_name']);
		}
		
		if(empty($app) || empty($cate) || $app['name']!=$cate['app_name']){   
			return false;
		}else{
			$app['cate_id'] = $cate['id'];
		}
		
		if(!empty($app['sets']['has_cate_sets'])){
			if(!empty($app['sets']['cate']['dir'])){
				$cate['publish'] = empty($cate['childs']) ? 1 : 0;
			}
			

			if( !empty($cate['sets']['base']) ){
				
				$app['sets']['base'] = array_merge($app['sets']['base'],$cate['sets']['base']);
				$app['sets']['tabs'] = array_merge($app['sets']['tabs'],$cate['sets']['base']);
			}
			
			foreach($app['sets']['tabs'] as $k=>$v){
				if($v){
					if(empty($app['sets'][$k])){
						$app['sets'][$k] = config('exts.'.$k.'.sets') ?? [];
					}
					$app['sets'][$k] = array_merge($app['sets'][$k],$cate['sets'][$k] ?? []);
				}else{
					$app['sets'][$k] = [];
				}
			}
			
			if(!empty($cate['sets']['app'])){
				$app['sets']['app'] = array_merge($app['sets']['app'],$cate['sets']['app']);
			}
		}
		return $app;
	}
}

if (! function_exists('get_cates')) {
	/**
	 * 获取应用信息
	 * @param  string  $field  
	 * @param  \App\Models\App||array||string $name
	 */
	function get_cates($app) {
			$app = get_app($app);
			if(empty($app)) return false;
			$cates = cate_model($app)->get();
			if(empty($cates)){
				return [];
			}else{
				$cates = $cates->toArray();
				if($app['sets']['has_cate_sets'] && !empty($app['sets']['cate']['dir'])){
					foreach($cates as &$cate){
						$cate['publish'] = empty($cate['childs']) ? 1 : 0;
					}
				}
				$cates = array_combine(array_column($cates,'id'),$cates); //分类列表，设id为key
				return $cates;
			}
	}
}

if (! function_exists('include_route_files')) {
    /**
     * Loops through a folder and requires all PHP files
     * Searches sub-directories as well.
     *
     * @param $folder
     */
    function include_route_files($folder)
    {
        try {
            $rdi = new recursiveDirectoryIterator($folder);
            $it = new recursiveIteratorIterator($rdi);
            while ($it->valid()) {
                if (! $it->isDot() && $it->isFile() && $it->isReadable() && $it->current()->getExtension() === 'php') {
                    require $it->key();
                }

                $it->next();
            }
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }
}


//取字段标题,字段必须设置在应用的fields中
if (! function_exists('get_app_field_name')) {
	function get_app_field_name($app,$name){
		$app=get_app($app);
		if($name){
			return $app['sets']['app']['fields'][$name] ?? __(ucfirst($name));
		}else{
			return $app['sets']['app']['fields'] ?? [];
		}
	}
}

if (! function_exists('get_file_type')) {
    function get_file_type($file)
    {   
		$fileTypes = [
			'image'  => '/^(gif|png|jpe?g|svg|bmp)$/i',
			'video'  => '/^(og?|mp4|webm|mp?g|mov|3gp|avi|flv)$/i',
			'audio'  => '/^(m4a|mp3|wav|wma|wmv|mid|midi)$/i',
			'office'  => '/^(csv|doc|docx|xls|xlsx|ppt)$/i',
			'zip'    => '/^(zip|rar|7z|jar|tar|gz)$/i',
		];		
		$filetype = '';
		$farr =  array_filter(str2arr($file,'/'));
		$file = end($farr);
		$arr = str2arr($file,'.');
		if(count($arr) >1 && !empty(end($arr))){
			$ext = end($arr);
			foreach ($fileTypes as $type => $pattern) {
				if (preg_match($pattern, $ext) === 1) {
					$filetype = $type;
					break;
				}
			}
			if(empty($filetype)) $filetype=$ext; //未找到类型直接返回扩展名.
		}
        return $filetype;
    }
}